package siscom.componentes;

/**
 *
 * @author Carlos Ribeiro
 */
/* FixedLengthDocument.java */


import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class FixedLengthDocument extends PlainDocument
{
    /**
	 * 
	 */
	private static final long serialVersionUID = -3027806599932860051L;
	private int     iMaxLength;
    private boolean upperCase;

    public FixedLengthDocument(int maxlen, boolean upperCase)
    {
        super();
        iMaxLength = maxlen;
        this.upperCase = upperCase;
    }
    public FixedLengthDocument(int maxlen)
    {
        super();
        iMaxLength = maxlen;
        this.upperCase = false;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr)
            throws BadLocationException {
    	if(getLength() + str.length() > iMaxLength && iMaxLength > 0 ) {
    		return;
    	}
        if (str == null)
            return;

        if (iMaxLength <= 0) // aceitara qualquer no. de caracteres
        {
			if (upperCase) {
				char[] upper = str.toCharArray();
				for (int i = 0; i < upper.length; i++) {
					upper[i] = Character.toUpperCase(upper[i]);
				}
				super.insertString(offset, new String(upper), attr);
				return;
			}
            super.insertString(offset, str, attr);
            return;
        }

        int ilen = (getLength() + str.length());
        if (ilen <= iMaxLength) { // se o comprimento final for menor...
			if (upperCase) {
				char[] upper = str.toCharArray();
				for (int i = 0; i < upper.length; i++) {
					upper[i] = Character.toUpperCase(upper[i]);
				}
				super.insertString(offset, new String(upper), attr);
			}
			else
				super.insertString(offset, str, attr); // ...aceita str
        }
        else
        {
            if (getLength() == iMaxLength)
                return; // nada a fazer
            String newStr = str.substring(0, (iMaxLength - getLength()));
			if (upperCase) {
				char[] upper = str.toCharArray();
				for (int i = 0; i < upper.length; i++) {
					upper[i] = Character.toUpperCase(upper[i]);
				}
				super.insertString(offset, new String(upper), attr);
			}
			else			
				super.insertString(offset, newStr, attr);
        }
    }
}
